import Global from "./global";

var Util = {};

Util.fetchPost = function (url, params = '', accountSid = Global.accountSid) {
    let header = {
        "Content-Type": "application/x-www-form-urlencoded",
    };
    url = Global.ServerUrl + url;
    console.log('request url:', url, params);  //打印请求参数
    if (params == '') {   //如果网络请求中没有参数
        return Promise.race([
            new Promise(function (resolve, reject) {
                fetch(url, {
                    method: 'post',
                    headers: header
                }).then((response) => {
                    if (response.ok) {
                        return response.json()
                    } else {
                        return Promise.reject({
                            status: response.status,
                            statusText: response.statusText
                        })
                    }
                })
                    .then((data) => {
                        console.log('res:', url, data);  //网络请求成功返回的数据
                        resolve(data);
                    })
                    .catch((err) => {
                        console.log('err:', url, err);     //网络请求失败返回的数据        
                        reject(err);
                    });
            }),
            new Promise(function (resolve, reject) {
                setTimeout(() => reject(new Error('request timeout')), 10000)
            })
        ]);
    } else {   //如果网络请求中带有参数
        return Promise.race([
            new Promise(function (resolve, reject) {
                var requestParam = "1=1";
                for (key in params) {
                    requestParam += ("&" + key + "=" + params[key]);
                }
                requestParam.replace("1=1&", "")
                console.log("requestParam=  ", requestParam);
                fetch(url, {
                    method: 'post',
                    headers: header,
                    body: requestParam   //body参数，通常需要转换成字符串后服务器才能解析
                }).then((response) => {
                    if (response.ok) {
                        return response.json()
                    } else {
                        return Promise.reject({
                            status: response.status,
                            statusText: response.statusText
                        })
                    }
                })
                    .then((data) => {
                        console.log('res:', url, data);   //网络请求成功返回的数据
                        resolve(data);
                    })
                    .catch((err) => {
                        console.log('err:', url, err);   //网络请求失败返回的数据  
                        reject(err);
                    });
            }),
            new Promise(function (resolve, reject) {
                setTimeout(() => reject(new Error('request timeout')), 10000)
            })
        ])
    }
}


Util.uploadImage = function (url, params) {
    let formData = new FormData();
    let file = {uri: params.uri, type: params.mime, name: params.uri.substring(params.uri.lastIndexOf("/"))};
    if (params.uid) {
        formData.append("uid", params.uid);
    }
    formData.append("pic", file);
    console.log('request url:', url, params);  //打印请求参数
    return new Promise(function (resolve, reject) {
        fetch(Global.ServerUrl + url, {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            body: formData,
        }).then((response) => response.json())
            .then((data) => {
                console.log('res:', url, data);   //网络请求成功返回的数据
                resolve(data);
            })
            .catch((err) => {
                console.log('err:', url, err);   //网络请求失败返回的数据  
                reject(err);
            });
    });
}

Util.uploadmultiImages = function (url, params) {
    let formData = new FormData();
    for (let key in params) {
        formData.append(key, params[key]);
    }
    console.log(formData)
    return new Promise(function (resolve, reject) {
        fetch(Global.ServerUrl + url, {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            body: formData,
        }).then((response) => response.json())
            .then((data) => {
                console.log('res:', url, data);   //网络请求成功返回的数据
                resolve(data);
            })
            .catch((err) => {
                console.log('err:', url, err);   //网络请求失败返回的数据
                reject(err);
            });
    });
}


/**
 * 获取当前时间与指定时间的时间差（毫秒值）
 */
Util.timeago = (dateTimeStamp) => {
    var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
    var hour = minute * 60;
    var day = hour * 24;
    var week = day * 7;
    var halfamonth = day * 15;
    var month = day * 30;

    var now = new Date().getTime();   //获取当前时间毫秒
    var diffValue = now - dateTimeStamp;//时间差

    if (diffValue < 0) {
        return;
    }

    var minC = diffValue / minute;  //计算时间差的分，时，天，周，月
    var hourC = diffValue / hour;
    var dayC = diffValue / day;
    var weekC = diffValue / week;
    var monthC = diffValue / month;

    if (monthC >= 1) {
        result = " " + parseInt(monthC) + "月前"
    } else if (weekC >= 1) {
        result = " " + parseInt(weekC) + "周前"
    } else if (dayC >= 1) {
        result = " " + parseInt(dayC) + "天前"
    } else if (hourC >= 1) {
        result = " " + parseInt(hourC) + "小时前"
    } else if (minC >= 1) {
        result = " " + parseInt(minC) + "分钟前"
    }
    else {
        result = "刚刚";
    }

    return result;
}
/**
 * 将字符串格式化为时间
 */
Util.strToDate = (dateString) => {
    var DATE_REGEXP = new RegExp("(\\d{4})-(\\d{2})-(\\d{2})([T\\s](\\d{2}):(\\d{2}):(\\d{2})(\\.(\\d{3}))?)?.*");
    if (DATE_REGEXP.test(dateString)) {
        var timestamp = dateString.replace(DATE_REGEXP, function ($all, $year, $month, $day, $part1, $hour, $minute, $second, $part2, $milliscond) {
            var date = new Date($year, $month - 1, $day, $hour || "00", $minute || "00", $second || "00", $milliscond || "00");
            return date.getTime();
        });
        var date = new Date();
        date.setTime(timestamp);
        return date;
    }
    return null;
}

Util.dateTostr = (date) => {
    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }
    return date.format('yyyy-MM-dd hh:mm:ss');
}

Util.getDays = (days, daysLater) => {
    Date.prototype.Format = function (fmt) { //author: meizz   
        var o = {
            "M+": this.getMonth() + 1,                 //月份   
            "d+": this.getDate(),                    //日   
            "h+": this.getHours(),                   //小时   
            "m+": this.getMinutes(),                 //分   
            "s+": this.getSeconds(),                 //秒   
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
            "S": this.getMilliseconds()             //毫秒   
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    let dateArr = [];
    let now = new Date().getTime();
    for (let i = 0; i < days; i++) {
        let dayTime = daysLater + i;
        let str;
        if (dayTime == 0) {
            str = '今天'
        } else if (dayTime == 1) {
            str = '明天'
        } else if (dayTime == 2) {
            str = '后天'
        } else {
            str = dayTime + '天后'
        }
        let day = new Date(now + 86400000 * i + 86400000 * daysLater);
        dateArr.push(day.Format('MM月dd日') + "(" + str + ")");
    }
    return dateArr
}

Util.ErrorMessage = "网络出现问题，请稍候再试。";


export default Util;